import { getToken, setToken, removeToken } from '@/utils/auth'
import { login } from '@/api/user'

export default {
    namespaced: true,    //namespaced:true代表该模块带有独立命名空间
    state: {             //否则，默认是处于全局命名空间，就和非模块化一样
        token: ''
    },
    mutations: {
        //更新state中token
        setToken(state, value) {
            state.token = value
        },
        //删除state中token
        removeToken(state, value) {
            state.token = value
        }
    },
    actions: {
        // 登录
        login(context, userInfo) {
            const { account, password } = userInfo
            return new Promise((resolve, reject) => {
                login({ account: account.trim(), password: password }).then(res => {
                    let { token } = res.data;
                    setToken(token)
                    context.commit('setToken', token)
                    resolve(res.data)
                }).catch(err => {
                    reject(err)
                })
            })

        },
        // 退出登录
        logout(context) {
            return new Promise((resolve, reject) => {
                removeToken()
                context.commit('setToken', '')
                resolve()
            })
        }
    },
    getters: {
        personList(state) {
            return state.personList
        }
    }
}
